import 'dart:io';
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:ileddemo/code/ui/image/EditGifPage.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image/image.dart' as img;
import 'dart:ui' as ui;
import 'package:lib_bt/BleManager.dart';
import '../../../AppGlobals.dart';
import '../../../generated/l10n.dart';
import '../../ble/protocol/AutoConnectUtil.dart';
import '../../ble/protocol/iledcolor/BleBean.dart';
import '../../ble/protocol/iledcolor/source/gif/GifDecoder.dart';
import '../../ble/protocol/iledcolor/source/gif/GifSourceBean.dart';
import '../../ble/protocol/iledcolor/source/graffiti/GraffitiSourceBean.dart';
import '../../ble/protocol/iledcolor/source/text/TextSourceBean.dart';
import '../../util/PermissionUtil.dart';
import '../base/BaseWidget.dart';
import '../base/TitleBarWidget.dart';
import '../connect/ConnectBlePage.dart';
import '../image/CropPage.dart';
import '../image/EditImagePage.dart';
import '../music/MusicPage.dart';
import '../playlist/PlayListPage.dart';
import '../setting/SettingPage.dart';
import '../source/SourcePage.dart';
import '../text/EditTextPage.dart';
import 'FunWidget.dart';

class IndexPage extends StatefulWidget {
  const IndexPage({super.key});

  @override
  State<IndexPage> createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage> {
  @override
  void initState() {
    SystemChrome.setSystemUIOverlayStyle(
      const SystemUiOverlayStyle(
        systemNavigationBarColor: Colors.white,
        systemNavigationBarIconBrightness: Brightness.dark,
        statusBarIconBrightness: Brightness.dark,
        statusBarBrightness: Brightness.light,
        statusBarColor: Colors.transparent,
      ),
    );
    super.initState();
  }

  Future openPage(Widget widget) {
    return Navigator.of(context).push(MaterialPageRoute(builder: (context) => widget));
  }

  //连接提示
  String getConnectTip() {
    var connectBleBeans = BleManager.instance.getConnectBleBeans();
    if (connectBleBeans.isEmpty) {
      return S.of(context).str_id_2;
    } else {
      return "${S.of(context).str_id_3} : ${connectBleBeans.length}";
    }
  }

  //获取屏幕尺寸
  Size getScreenSize() {
    var bleBean = BleBean(bean: AutoConnectUtil.instance.getLastConnectBleBean());
    var size = Size(bleBean.width.toDouble(), bleBean.height.toDouble());
    return size;
  }

  List<Widget> getFunWidget() {
    List<Widget> list = [];
    //图片
    list.add(
      FunWidget(
        title: S.of(context).str_id_1,
        onTap: () async {
          final isGranted = await PermissionUtil.instance.checkCameraPermission(context);
          if (!isGranted) {
            print("没有授权访问相册");
            return;
          }
          final ImagePicker picker = ImagePicker();
          // Pick an image.
          final XFile? image = await picker.pickImage(source: ImageSource.gallery);
          if (image != null) {
            var bleBean = BleBean(bean: AutoConnectUtil.instance.getLastConnectBleBean());
            var size = Size(bleBean.width.toDouble(), bleBean.height.toDouble());
            var fileByte = File(image.path).readAsBytesSync();
            //裁剪
            var imageList = await openPage(CropPage(screenSize: size, imageData: fileByte));
            if (imageList != null && imageList.isNotEmpty) {
              if (GifDecoder.isGif(fileByte)) {
                //gif节目
                // 创建 ImageDecoder
                final ui.Codec codec = await ui.instantiateImageCodec(fileByte);

                // 解码 GIF 的每一帧
                List<int> delays = [];
                for (int i = 0; i < codec.frameCount; i++) {
                  final ui.FrameInfo frameInfo = await codec.getNextFrame();
                  int time = max(frameInfo.duration.inMilliseconds, 20) ~/ 10;
                  delays.add(time);
                }
                //合成gif
                var filePath = await GifDecoder.case2Gif(imageList, delays);
                GifSourceBean gifSourceBean = GifSourceBean();
                gifSourceBean.screenSize = size;
                gifSourceBean.setImagePath(filePath);

                for (var i = 0; i < imageList.length; i++) {
                  gifSourceBean.frameList.add(
                    GraffitiSourceBean.formImage(
                      await GifDecoder.case2ImgImage(imageList[0], isSingleColor: bleBean.isSingleColor()),
                    ),
                  );
                }

                openPage(EditGifPage(sourceBean: gifSourceBean));
              } else {
                //图片节目
                var source = GraffitiSourceBean.formImage(
                  await GifDecoder.case2ImgImage(imageList[0], isSingleColor: bleBean.isSingleColor()),
                );
                openPage(EditImagePage(sourceBean: source));
              }
            }
          }
        },
      ),
    );
    //文字
    list.add(
      FunWidget(
        title: S.of(context).str_id_18,
        onTap: () => openPage(
          EditTextPage(
            sourceBean: TextSourceBean()
              ..screenSize = getScreenSize()
              ..textHeight = getScreenSize().height.toInt(),
          ),
        ),
      ),
    );
    //音乐
    list.add(
      FunWidget(
        title: S.of(context).str_id_25,
        onTap: () async {
          var checkMusicPermission = await PermissionUtil.instance.checkMusicPermission(context);
          if (checkMusicPermission) {
            openPage(const MusicPage());
          }
        },
      ),
    );

    //素材库
    list.add(FunWidget(title: S.of(context).str_id_33, onTap: () => openPage(const SourcePage())));
    //播放列表
    list.add(FunWidget(title: S.of(context).str_id_35, onTap: () => openPage(const PlayListPage())));
    //设置
    list.add(FunWidget(title: S.of(context).str_id_21, onTap: () => openPage(const SettingPage())));

    return list;
  }

  @override
  Widget build(BuildContext context) {
    AppGlobals.rootContext = context;
    var funWidget = getFunWidget();
    return WillPopScope(
      onWillPop: () async {
        return false;
      },
      child: BaseWidget(
        child: Column(
          children: [
            //连接按钮
            GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () async {
                //开始扫描
                bool flag = await PermissionUtil.instance.checkBlePermission(context);
                if (!flag) {
                  return;
                }
                openPage(const ConnectBlePage());
              },
              child: ListenableBuilder(
                listenable: BleManager.instance,
                builder: (context, child) {
                  return Container(
                    alignment: Alignment.center,
                    height: 50,
                    decoration: const BoxDecoration(color: Colors.blueGrey),
                    child: Text(getConnectTip(), style: const TextStyle(fontSize: 16)),
                  );
                },
              ),
            ),
            const SizedBox(height: 10),
            Expanded(
              child: Container(
                margin: const EdgeInsets.only(left: 16, right: 16),
                child: GridView.count(
                  crossAxisCount: 2,
                  crossAxisSpacing: 25.0,
                  mainAxisSpacing: 10,
                  childAspectRatio: 1,
                  children: List.generate(funWidget.length, (index) {
                    return funWidget[index];
                  }),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
